package com.lym.order.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.lym.order.bean.Order;
import com.lym.order.feign.ProductFeignClient;
import com.lym.order.service.OrderService;
import com.lym.product.bean.Product;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * 订单服务实现类
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    LoadBalancerClient loadBalancerClient;

    @Autowired
    ProductFeignClient productFeignClient;

    /**
     * 创建订单
     *
     * @param productId
     * @param userId
     * @return
     */
    @SentinelResource(value = "createOrder", blockHandler = "createOrderBlockHandler")
    @Override
    public Order createOrder(Long productId, Long userId) {
        /**
         * 远程调用获取商品信息
         */
        // 默认选择第一个实例
//        Product product = getProductFromRemote(productId);
        // 负载均衡获取实例
//        Product product = getProductFromRemoteWithLoadBalancer(productId);
        // 基于注解的负载均衡获取实例
//        Product product = getProductFromRemoteWithLoadBalancerAnnotation(productId);

        /**
         * 使用Feign远程调用获取商品信息
         */
        Product product = productFeignClient.getProductById(productId);

        Order order = new Order();
        order.setId(1L);
        // 订单总金额
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setUserId(userId);
        order.setNickName("小明");
        order.setAddress("北京");
        // 订单商品列表
        order.setProductList(Arrays.asList(product));

        return order;
    }

    /**
     * 兜底回调
     * 注: 该方法名必须与createOrder方法的注解@SentinelResource中的blockHandler属性值相同
     *
     * @param productId
     * @param userId
     * @param e
     * @return
     */
    public Order createOrderBlockHandler(Long productId, Long userId, BlockException e) {
        Order order = new Order();
        order.setId(0L);
        order.setTotalAmount(new BigDecimal(0));
        order.setUserId(userId);
        order.setNickName("未知用户");
        order.setAddress("异常信息：" + e.getClass());
        return order;
    }

    /**
     * 远程调用获取商品信息
     * 注: 演示远程调用基本实现, 实际开发中需要做重试、负载均衡等
     *
     * @param productId
     * @return
     */
    private Product getProductFromRemote(Long productId) {
        // 1、获取到商品服务所在的所有机器IP+port
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");

        ServiceInstance instance = instances.get(0); // 随机获取一个
        // 远程URL地址 http://localhost:9000/product/2
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;
        log.info("远程请求: {}", url);

        // 2、给远程发送请求
        Product product = restTemplate.getForObject(url, Product.class);

        return product;
    }

    // 进阶: 完成负载均衡发送请求
    private Product getProductFromRemoteWithLoadBalancer(Long productId) {
        // 1、获取到商品服务所在的所有机器IP+port
        ServiceInstance choose = loadBalancerClient.choose("service-product");
        // 远程URL地址 http://localhost:9000/product/2
        String url = "http://" + choose.getHost() + ":" + choose.getPort() + "/product/" + productId;
        log.info("远程请求: {}", url);

        // 2、给远程发送请求
        Product product = restTemplate.getForObject(url, Product.class);

        return product;
    }

    // 进阶2: 基于注解的负载均衡
    private Product getProductFromRemoteWithLoadBalancerAnnotation(Long productId) {
        String url = "http://service-product/product/" + productId;

        // 给远程发送请求: service-product会被动态替换成为服务地址
        Product product = restTemplate.getForObject(url, Product.class);

        return product;
    }

}
